package com.brook.springbootsrcurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Brook
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    /**
     * 系统的默认访问路径，跳转到/login，此url为spring security提供
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/login");
    }

    /**
     * 自行注入一个PasswordEncoder
     * @return
     */
    @Bean
    public PasswordEncoder getPassWordEncoder() {
        //return new BCryptPasswordEncoder(10);
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 自行注入一行UserDetailsService
     * 如果没有的话，在UserDetailsServiceAutoConfiguration中会默认
     * 注入一个包含user用户的InMemoryUser
     * 另外也可以采用修改configure(AuthenticationManagerBuilder auth) 方法并注入authenticationManager
     */
    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(User.withUsername("admin").password("admin").authorities("mobile", "salary").build(),
                User.withUsername("manager").password("manager").authorities("salary").build(),
                User.withUsername("worker").password("worker").authorities("worker").build());
        return userDetailsManager;
    }
}
